import React, {useEffect, useState} from 'react';
import {Breadcrumb, Layout, Button, Space, Switch, message, Input, Popconfirm, Modal, Form, Drawer} from 'antd'
import {useNavigate} from 'react-router-dom'
import Mytable from "../../../pages/Mytable";
import {getAllUserByPage, changeStatus, deleteUser} from "../../../api/user";
import {changePassword} from "../../../api/changePassword";
import EditUrls from "../Users/EditUrls";

const {Content} = Layout;
const {Search} = Input;

function Users() {
    const columns = [
        {
            title: '用户名',
            width: '50vh',
            dataIndex: 'username',
        },
        {
            title: '用户是否授权',
            dataIndex: 'is_active',
            render: (_, record) => (<Switch
                checkedChildren="授权"
                unCheckedChildren="禁用"
                defaultChecked={record.is_active === 1}
                disabled={record.username === sessionStorage.getItem("username")}
                onClick={changeState(record.id, record.is_active)}
            />)
        },
        {
            title: '操作',
            dataIndex: 'repayment',
            render: (_, record) => (<Space>
                <Button type='primary' onClick={() => {
                    setUsername(record.username)
                    setVisible(true)
                }}>修改密码</Button>
                <Button type='primary' onClick={() => {
                    setId(record.id)
                    setDrawerVisible(true)
                }}>路由授权</Button>
                <Popconfirm title="确认删除？" okText="确认" cancelText="取消" onConfirm={() => {
                    deleteUser(record.id).then(response => {
                        const res = response.data
                        message.success(res.msg)
                        paginationChange(1, 10)
                    })
                }
                }
                            disabled={record.username === sessionStorage.getItem('username')}>
                    <Button type='danger' disabled={record.username === sessionStorage.getItem('username')}>删除</Button></Popconfirm>
            </Space>)
        }
    ];
    const [data, setData] = useState([]);
    const [total, setTotal] = useState(0);
    const [page, setPage] = useState({current: 1, pageSize: 10, value: ''})
    const [visible, setVisible] = useState(false);
    const [drawerVisible, setDrawerVisible] = useState(false);
    const [username, setUsername] = useState('')
    const [id, setId] = useState('')
    const [loading, setLoading] = useState(false);
    const [form] = Form.useForm();
    const pagination = {
        onShowSizeChange: (current, pageSize) => {
            paginationChange(current, pageSize, page.value)
        },
        onChange: (current, pageSize) => {
            paginationChange(current, pageSize, page.value)
        },
        showSizeChanger: true,
        total,
        current: page.current,
        pageSize: page.pageSize,
        defaultPageSize: 10,
        pageSizeOptions:
            [5, 10, 15, 20]
    }
    const paginationChange = async (current, pageSize, value) => {
        setPage({
            current,
            pageSize,
            value
        })
    }
    const changeState = (id, is_active) => {
        return () => {
            changeStatus({id, is_active: is_active === 0 ? 1 : 0}).then(response => {
                const res = response.data
                message.success(res.msg)
            })
        }
    }
    useEffect(() => {
        setLoading(true)
        getAllUserByPage(page).then(response => {
            const {records, total} = response.data.data
            setData(records)
            setTotal(total)
            setLoading(false)
        })
    }, [page])
    const navigate = useNavigate()
    return (
        <Layout style={{padding: '0 24px 24px'}}>
            <Breadcrumb style={{margin: '16px 0'}}>
                <Breadcrumb.Item onClick={() => navigate("/main")}>首頁</Breadcrumb.Item>
                <Breadcrumb.Item>人员管理</Breadcrumb.Item>
            </Breadcrumb>
            <Content
                className="site-layout-background"
                style={{
                    padding: 24,
                    margin: 0,
                    minHeight: 280,
                }}
            >
                <div style={{marginBottom: '20px', float: 'right'}}>
                    <Search placeholder="输入姓名查找" onSearch={(value) => {
                        paginationChange(1, page.pageSize, value)
                    }} style={{width: 200}}/>
                </div>
                <Mytable
                    columns={columns}
                    dataSource={data}
                    pagination={pagination}
                    bordered
                    loading={loading}
                />
            </Content>
            <Modal
                title="修改密码"
                visible={visible}
                onCancel={() => {
                    form.resetFields()
                    setVisible(false)
                }}
                closable={false}
                cancelText={'取消'}
                okText={'确认'}
                onOk={async () => {
                    try {
                        const {password,rePassword} = await form.validateFields()
                        if(password!==rePassword){
                            message.error('两次密码不一致')
                            return
                        }
                        changePassword({username, password}).then(response => {
                            const res = response.data
                            message.success(res.msg)
                            form.resetFields()
                            setVisible(false)
                        }).catch(error => {
                            message.error(error)
                        })
                    } catch (e) {
                        message.error('请输入正确的数据')
                    }
                }}
            >
                <Form
                    name="basic"
                    labelCol={{span: 8}}
                    initialValues={{remember: true}}
                    autoComplete="off"
                    layout={'vertical'}
                    form={form}
                >
                    <Form.Item
                        label="密码"
                        name="password"
                        rules={[{required: true, message: '请输入密码'}, {min: 8, message: '密码最小为8位'}]}
                    >
                        <Input.Password/>
                    </Form.Item>
                    <Form.Item
                        label="再次输入密码"
                        name="rePassword"
                        rules={[{required: true, message: '请输入密码'}, {min: 8, message: '密码最小为8位'}]}
                    >
                        <Input.Password/>
                    </Form.Item>
                </Form>
            </Modal>
            <Drawer
                title={`路由授权`}
                placement="right"
                size={'large'}
                onClose={()=>{setDrawerVisible(false)}}
                visible={drawerVisible}
            >
                <EditUrls id={id}/>
            </Drawer>
        </Layout>
    );
}

export default Users;
